<?php 
namespace Core\Application;

use Core\Debugger\AlertLevel;
use Core\Debugger\LogEntry;
use \Core\Debugger\Logger;

/**
 * Provides methodes for the routes management. This class cannot be inherits.
 * @namespace Core\Application
 * @author Raphael DE FREITAS (RaphyTheGeek@gmail.com)
 * @version 1.0
 *
 */
final class Router
{
	protected $_Routes = array();

	protected static $_Instance = null;
	
	private function _construct() {

	}
	
	public static function getInstance() {
		if(is_null(self::$_Instance))
			self::$_Instance = new Router;
		return self::$_Instance;
	}
	
	/**
	 * Load routes from the routes file specified.
	 * @param string $file Path of the routes file.
	 */
	public function addFromFile($file) {
		Logger::log(new LogEntry('Reading routes file '.str_replace(ROOT, './', $file).'...'));
		$xml = new \DOMDocument;
		$xml->load($file);
		$routes = $xml->getElementsByTagName('route');
		
		foreach($routes as $route) {
			$vars = array();
			if ($route->hasAttribute('vars'))
				$vars = explode(',', $route->getAttribute('vars'));
			if ($route->hasAttribute('uri') && $route->hasAttribute('module') && $route->hasAttribute('controller') && $route->hasAttribute('action'))
				$this->_Routes[] = new Route($route->getAttribute('uri'), $route->getAttribute('module'), $route->getAttribute('controller'), $route->getAttribute('action'), $vars);
		}
	}
	
	/**
	 * Try to find a match in the routes to obtain this last one with the specified URI.
	 * @param string $uri The URI which have to checked.
	 * @return Route if matched; otherwhise, FALSE.
	 */
	public function match($url) {
		foreach ($this->_Routes as $route) {
			if(($var_values = $route->match($url)) !== false) {
				if($route->hasVars()) {
					array_shift($var_values);
					$route->setVars(array_combine($route->getVars(), $var_values));
				}
				return $route;
			}
		}
		return false;
	}
}
?>